import logging
import random
import string


def ensure_bytes(value):
    if hasattr(value, 'encode'):
        value = value.encode('utf8')
    return value


class ContextAdapter(logging.LoggerAdapter):
    def process(self, msg, kwargs):
        context = self.get_context_summary(self.extra)
        return f'{context} {msg}', kwargs

    @staticmethod
    def get_context_summary(context):
        return ' '.join(f'[{key}: {value}]' for key, value in context.items())


def random_string(length=4):
    seq = string.ascii_letters + string.digits
    return ''.join(random.choice(seq) for _ in range(length))
